package com.andy.module.ext

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.andy.module.network.ApiPagerResponse
import com.andy.module.network.ApiResponse
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.*
import com.andy.network.base.BaseViewModel
import me.hgj.jetpackmvvm.ext.util.loge
import me.hgj.jetpackmvvm.network.AppException
import me.hgj.jetpackmvvm.network.BaseResponse
import me.hgj.jetpackmvvm.state.ResultState
import me.hgj.jetpackmvvm.state.paresException

/**
 * @creator:LuoFan
 * @date:2022/6/2
 * @description:
 */

fun <T> BaseViewModel.requestAsync(
    scope: CoroutineScope,
    request: suspend () -> ApiResponse<T>
): Deferred<suspend () -> ApiResponse<T>> {
    return scope.async {
        request
    }
}

suspend fun <T> BaseViewModel.awaitResult(deferred: Deferred<suspend () -> ApiResponse<T>>): T? {
    return deferred.await().invoke().getResponseData()
}

fun <T> BaseViewModel.genLiveData() = MutableLiveData<ResultState<T>>()

fun BaseViewModel.requestAny(
    block: suspend () -> BaseResponse<Any>, resultState: MutableLiveData<ResultState<Any>>,
    isShowDialog: Boolean = true,
): Job {
    return viewModelScope.launch {
        runCatching {
            if (isShowDialog) loadingValue.showDialog.postValue("")
            //请求体
            block()
        }.onSuccess { result ->
            if (isShowDialog) loadingValue.dismissDialog.postValue(true)
            if (result.isSuccess()) {
                resultState.value = ResultState.onAppSuccess(Any())
            } else {
                resultState.value = ResultState.onAppError(AppException(result.getResponseCode(), result.getResponseMsg()))
            }
        }.onFailure {
            if (isShowDialog) loadingValue.dismissDialog.postValue(true)
            it.message?.loge()
            //打印错误栈信息
            it.printStackTrace()
            ToastUtils.showLong(it.message)
        }
    }
}

fun <T> BaseViewModel.requestPage(
    block: suspend () -> BaseResponse<ApiPagerResponse<T>>,
    resultState: MutableLiveData<ResultState<MutableList<T>>>,
    isShowDialog: Boolean = false,
    loadingMessage: String = "请求网络中..."
): Job {
    return viewModelScope.launch {
        runCatching {
            if (isShowDialog) resultState.value = ResultState.onAppLoading(loadingMessage)
            //请求体
            block()
        }.onSuccess {
            resultState.paresResult(it)
        }.onFailure {
            it.message?.loge()
            //打印错误栈信息
            it.printStackTrace()
            resultState.paresException(it)
        }
    }
}

/**
 * 处理返回值
 * @param result 请求结果
 */
private fun <T> MutableLiveData<ResultState<MutableList<T>>>.paresResult(result: BaseResponse<ApiPagerResponse<T>>) {
    value = when {
        result.isSuccess() -> {
            result.getResponseData()?.let {
                ResultState.onAppSuccess(it.datas)
            } ?: let {
                ResultState.onAppError(AppException(result.getResponseCode(), result.getResponseMsg()))
            }
        }
        else -> {
            ResultState.onAppError(AppException(result.getResponseCode(), result.getResponseMsg()))
        }
    }
}